package org.jgs1904.practice;

/**
 * @author: 默苍璃
 * @date: 2022-09-16 09:44
 */
public class StringBuilderPractice {

    public static void main(String[] args) {
        String[] fields = {"name", "position", "salary"};
        String table = "employee";
        String insert = buildInsertSql(table, fields);
        System.out.println(insert);
        System.out.println(
                "INSERT INTO employee (name, position, salary) VALUES (?, ?, ?)".equals(insert) ? "测试成功" : "测试失败");
    }


    /**
     * 使用StringBuilder构造一个INSERT语句
     *
     * @param table
     * @param fields
     * @return
     */
    static String buildInsertSql(String table, String[] fields) {
        StringBuilder stringBuilder = new StringBuilder("INSERT INTO ");
        stringBuilder.append(table).append(" (");
        for (int i = 0; i < fields.length; i++) {
            String field = fields[i];
            //最后一个字段
//            if (i == fields.length - 1) {
//                stringBuilder.append(field);
//                break;
//            }
            stringBuilder.append(field).append(", ");
        }
        stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length());
        stringBuilder.append(") VALUES (?, ?, ?)");
        return String.valueOf(stringBuilder);
    }

}
